package com.iwhalecloud.bss.kite.cucc.service.pos.bcmc.handler.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import org.springframework.stereotype.Service;

import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.iwhalecloud.bss.kite.client.dto.inst.InstAttrDTO;
import com.iwhalecloud.bss.kite.common.constant.ServiceOfferConsts;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteObjectUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.attr.ILocalQueryScenePersonInfoService;
import com.iwhalecloud.bss.kite.cucc.client.api.reception.ICustReceptionService;
import com.iwhalecloud.bss.kite.cucc.client.dto.order.KiteCustomerInfoReq;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosAccountDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosCustomerDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.scene.CuccCustInfoDTO;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.dataservice.cache.ExtOrderInfoCache;
import com.iwhalecloud.bss.kite.cucc.service.pos.bcmc.BcmcPosContext;
import com.iwhalecloud.bss.kite.cucc.service.pos.handler.CuccPosServiceUtils;
import com.iwhalecloud.bss.kite.cucc.service.util.ChangeTypeUtils;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.enums.ActionType;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInstAcct;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import com.ztesoft.bss.common.util.ContextUtil;
import com.ztesoft.bss.common.util.SpringUtil;

/**
 * <Description> <br>
 * 组装报文账户信息节点
 *
 * @author XXZ<br>
 * @version 1.0<br>
 * @taskId <br>
 * @CreateDate 2020年12月15日 <br>
 * @since R9.0<br>
 * @see com.iwhalecloud.bss.kite.cucc.service.pos.bcmc.handler.impl <br>
 */
@Service
public class BcmcPosAccountHandler extends AbstractBcmcPosHandler {

    @Override
    public void doHandle(BcmcPosContext context) {
        List<KitePosAccountDTO> accounts = new ArrayList<KitePosAccountDTO>();
        context.getPosDto().setAccounts(accounts);
        IQuerySceneInstService querySceneInstService = SpringUtil.getBean(IQuerySceneInstService.class);

        // 账户ID集合，用于去重判断
        List<String> accountIds = Lists.newArrayList();
        List<KiteOfferInst> offerInsts = querySceneInstService.listMainOfferInsts(context.getSceneInstId());
        offerInsts.forEach(offerInst -> {
            List<KiteOfferInstAcct> offerInstAcctRels = querySceneInstService.listOfferInstAccts(context.getCustId(),
                offerInst.getOfferInstId());
            if (!Objects.isNull(offerInstAcctRels)) {
                // 获取有效账户信息
                offerInstAcctRels = offerInstAcctRels.stream()
                    .filter(acct -> !KiteStringUtils.equals(acct.getActionType().name(), ActionType.X.name()))
                    .collect(Collectors.toList());

                offerInstAcctRels.forEach((offerInstAcctRel) -> {
                    if (!accountIds.contains(offerInstAcctRel.getAcctId())) {
                        accountIds.add(offerInstAcctRel.getAcctId());
                        accounts.add(packageOfferInstAcct(context, offerInstAcctRel));
                    }
                });
            }
        });
    }

    /**
     * Description: <br>
     * 组装销售品账户信息节点
     *
     * @return <br>
     */
    private KitePosAccountDTO packageOfferInstAcct(BcmcPosContext context, KiteOfferInstAcct offerInstAcctRel) {
        KitePosAccountDTO account = new KitePosAccountDTO();

        account.setInstanceId(offerInstAcctRel.getInstId());
        account.setAccountId(offerInstAcctRel.getAcctId());
        account.setName(offerInstAcctRel.getAcctName());
        // 账户类型
        account.setPayMode(offerInstAcctRel.getPayModeCode());
        // 省份编码
        account.setProvinceCode(offerInstAcctRel.getProvinceCode());
        // 地市编码
        account.setEparchyCode(offerInstAcctRel.getEparchyCode());
        account.setIsGroupAccount(offerInstAcctRel.getIsDefault());
        // 设置操作类型
        account.setChangeType(ChangeTypeUtils.getChangeType(offerInstAcctRel.getActionType().name()));

        KitePosDTO oldPosDto = ExtOrderInfoCache.get(context.getSceneInstId());
        // 设置bssId、cbssId
        if (Objects.nonNull(oldPosDto)) {
            KitePosCustomerDTO customerDto = oldPosDto.getCustomer();
            if (!KiteObjectUtils.isEmpty(customerDto)) {
                account.setBssId(customerDto.getBssId());
                account.setCbssId(customerDto.getCbssId());
            }
        }

        KiteSceneInst sceneInst = CuccPosServiceUtils.getSceneInst(context);
        // 过户业务特殊处理
        if (ServiceOfferConsts.SERVICE_OFFER_TRANSFER.equals(sceneInst.getServiceOfferId())) {
            setAccountForChangeCust(context, account, sceneInst);
        }

        return account;
    }

    // 过户业务设置账户信息
    private void setAccountForChangeCust(BcmcPosContext context, KitePosAccountDTO account, KiteSceneInst sceneInst) {
        ILocalQueryScenePersonInfoService queryScenePersonService = SpringUtil
            .getBean(ILocalQueryScenePersonInfoService.class);
        IQuerySceneInstService querySceneInstService = SpringUtil.getBean(IQuerySceneInstService.class);
        // 从缓存里面取
        String sceneInstId = context.getSceneInstId();
        List<InstAttrDTO> attrConfigs = queryScenePersonService
            .listKiteConfigAttrs(sceneInstId, LocalKeyConsts.TRANSFER_DISPLAY_OBJECT_TYPE).getResultObject().stream()
            .filter(instAttrDTO -> LocalKeyConsts.KITE_ATTR_CONFIG_SHOW_TYPE_D.equals(instAttrDTO.getShowType()))
            .collect(Collectors.toList());
        Map<String, String> orderAttrMap = new HashMap<String, String>();
        attrConfigs.forEach(orderAttr -> orderAttrMap.put(orderAttr.getFieldName(), orderAttr.getValue()));
        account.setBssId(orderAttrMap.get("provinceAcctId"));
        account.setCbssId(orderAttrMap.get("cbssAcctId"));
        String isDefault = orderAttrMap.get("is_trans_acct");
        if (KiteStringUtils.isEqual(isDefault, "1")) {
            account.setChangeType("9");
            account.setCustId("");
        }
        else {
            account.setChangeType("");

            Map<String, Object> extParameter = querySceneInstService.getExtParameter(sceneInstId);
            Object newCust = extParameter.get(sceneInstId + "_transNewCustDTO");
            CuccCustInfoDTO newCustDto = Objects.nonNull(newCust) ? (CuccCustInfoDTO) newCust
                : queryNewCustInfo(sceneInst.getNewCustId());
            account.setCustId(newCustDto.getCustId());
        }
        account.setIsCenterDirectSign("0");
        account.setAcctContractCode(orderAttrMap.get("acctContractCode"));

    }

    /**
     * 查询客户信息
     */
    private CuccCustInfoDTO queryNewCustInfo(String custId) {
        KiteCustomerInfoReq kiteCustomerInfoReq = new KiteCustomerInfoReq();
        CuccCustInfoDTO cuccCustInfoDTO = new CuccCustInfoDTO();
        kiteCustomerInfoReq.setCustId(custId);
        String staffCode = ContextUtil.getSimpleLoginInfo().getStaffCode();
        String eparchyCode = ContextUtil.getSimpleLoginInfo().getLanId();
        String provinceCode = ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr();
        kiteCustomerInfoReq.setStaffCode(staffCode);
        kiteCustomerInfoReq.setEparchyCode(eparchyCode);
        kiteCustomerInfoReq.setProvinceCode(provinceCode);
        kiteCustomerInfoReq.setPageNum(1);
        kiteCustomerInfoReq.setPageSize(10);

        ICustReceptionService custReceptionService = SpringUtil.getBean(ICustReceptionService.class);
        // 调用查询客户列表
        PageInfo<CuccCustInfoDTO> list = custReceptionService.customerListQuery(kiteCustomerInfoReq);
        if (!KiteObjectUtils.isEmpty(list) && KiteListUtils.isNotEmpty(list.getList())) {
            List<CuccCustInfoDTO> cuccCustInfoDTOList = list.getList();
            cuccCustInfoDTO = cuccCustInfoDTOList.get(0);
        }
        return cuccCustInfoDTO;
    }
}
